#pragma once

#include <sys/epoll.h>
#include "log.hpp"
#include <iostream>
#include <cstring>

// 对Epoll的接口进行封装
// 1. 创建epoll模型
// 2. 进行等待
// 3. 增删改

using namespace Logspace;

enum 
{
    EPOLL_CREATE_Err,
};


class Epoll
{
public:
    Epoll()
    {
        // 创建一个epoll模型
        epollfd_ = epoll_create(1);
        if(epollfd_ < 0)
        {
            Log(Fatal) << "epoll_create error";
            exit(EPOLL_CREATE_Err);
        }
    }

    int wait(struct epoll_event*  events , int max_size , int timeout)
    {
        // 进行等待
        int n = epoll_wait(epollfd_ , events , max_size , timeout );
        return n;
    }


    void add(int fd , uint32_t new_evevts)
    {
        struct epoll_event epevt;
        epevt.events = new_evevts;
        epevt.data.fd = fd;

        if(epoll_ctl(epollfd_ , EPOLL_CTL_ADD , fd  , &epevt) < 0)
        {
            Log(Warning) << "epoll_ctl_add error , message : " << strerror(errno); 
        }
        Log(Info) << "epoll_ctl_add sucess , fd : " << fd; 
    }

    void del(int fd)
    {
        if(epoll_ctl(epollfd_ , EPOLL_CTL_DEL , fd  , nullptr) < 0)
        {
            Log(Warning) << "epoll_ctl_del error , message : " << strerror(errno); 
        }
        Log(Info) << "epoll_ctl_del sucess , fd : " << fd; 
    }

    void mod(int fd , uint32_t new_evevts)
    {
        struct epoll_event epevt;
        epevt.events = new_evevts;
        epevt.data.fd = fd;

        if(epoll_ctl(epollfd_ , EPOLL_CTL_MOD , fd  , &epevt) < 0)
        {
            Log(Warning) << "epoll_ctl_mod error , message : " << strerror(errno); 
        }
        Log(Info) << "epoll_ctl_mod sucess , fd : " << fd; 
    }
    
private:
    int epollfd_;
};
